<template>
  <div class="bank-container" v-loading="allBankLoading">
    <!-- 我的题库 -->
    <div class="qs-bank">
        <div class="bank-title">
          我的题库
          <el-button type="primary" link @click="handleCheckBank">查看</el-button>
        </div>
        <el-button style="width: 100%;margin-bottom:10px;" @click="batchAddOpen = true">批量添加</el-button>
        <div class="questions-bank">
          <div class="tree-header">
              <span class="tree-header-title">题库分组</span>
              <el-button type="primary" link @click="toggleExpand">{{ expandTree ? '全部收起' : '全部展开' }}</el-button>
          </div>
          <el-tree
          ref="treeRef"
          :data="ptreeData"
          :props="defaultProps"
          node-key="id"
          :default-expand-all="expandTree"
          class="tree-content"
          @node-click="handleClickOuterNode"
          >
              <template #default="{ node, data }">
                  <div class="custom-tree-node">
                      <div class="tree-node-label" :style="{ paddingLeft: (node.level - 1) * 10 + 'px' }" :title="node.label">
                        <i class="iconfont">&#xe6a7;</i>  
                        {{ node.label }}
                      </div>
                      <div class="tree-num" v-if="node.isLeaf">
                          （{{data.questionNum}}题）
                      </div>
                  </div>
              </template>
          </el-tree>
        </div>
      </div>
    <!-- 我的题库弹框 -->
    <el-dialog
      v-model="dialogVisible"
      title="我的题库"
      width="60%"
      class="myQsBank-dialog"
    >
      <div class="section-actions">
          <div class="actions-left">
              <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />
          </div>
      </div>
      <el-row class="content-box">
          <!-- 题库 -->
          <el-col :span="5" class="menu-tree-box">
              <div class="tree-header">
                  <span class="tree-header-title">题库分组</span>
                  <el-button type="primary" link @click="toggleExpand">{{ expandTree ? '全部收起' : '全部展开' }}</el-button>
              </div>
              <el-scrollbar height="400px">
                  <el-tree
                  ref="treeRef"
                  :data="tabArr"
                  :props="defaultProps"
                  node-key="id"
                  :default-expand-all="expandTree"
                  class="tree-content"
                  @node-click="handleClickNode"
                  >
                      <template #default="{ node, data }">
                          <div class="custom-tree-node">
                              <div class="tree-node-label" :style="{ paddingLeft: (node.level - 1) * 10 + 'px' }" :title="node.label">
                                  <i class="iconfont">&#xe6a7;</i>
                                  {{ node.label }}
                              </div>
                              <div class="tree-num" v-if="node.isLeaf">
                                  （{{data.questionNum || 0}}题）
                              </div>
                          </div>
                      </template>
                  </el-tree>
              </el-scrollbar>
          </el-col>
          <!-- 题目 -->
          <el-col :span="19" class="qs-table">
              <div class="user-table-top">
                  <div class="top-left">
                      <span class="curOStructure" v-if="curGroup">{{ curGroup.title }}</span>
                      <span class="user-default-show" v-else>未选择题库分组</span>
                      <span class="user-total">{{ `（${tableData?.length || 0}题）` }}</span>
                  </div>
              </div>
              <div class="qs-list">
                  <RuifoxTable 
                  :loading="tableLoading" 
                  v-model:tableData="tableData" 
                  v-model:fieldList="fieldList"
                  :default-index="true" 
                  :default-checkbox="true" 
                      @handleSearch="handleSearch">
                      <template #default-checkbox="{ element }">
                          <div class="table-div-check">
                              <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
                          </div>
                      </template>
                      <template #compName="{ element }">
                          {{element.cmp.compName}}
                      </template>
                      <template #options="{ element }">
                          <div class="table-td-option unmover">
                              <el-button type="primary" link @click="formCmpClick(element.cmp)">使用</el-button>
                          </div>
                      </template>
                  </RuifoxTable>
              </div>
              <PaginationView
              :total="queryData.total"
              :pageSize="queryData.pageSize"
              :currentPage="queryData.currentPage"
              :allChoose="isAllChooseBtn"
              :pageChoose="isPageChooseBtn"
              :checkedNum="checkedNum"
              :options="batchOptions"
              @changeSize="handleSizeChange"
              @currentChange="handleCurrentChange"
              @changePageChoose="handlePageChoose"
              @changeAllChoose="handleAllChoose"
              @cancelChoose="handleResetPagination"
              @invertChoose="handleInvertChoose"
              @refreshList="getTableData"
              @checkOption="handleBatchOptions"
              />
          </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchUse">使用</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量添加试题 -->
    <el-dialog title="批量导入" v-model="batchAddOpen" width="48%" class="batch-dialog">
      <div class="batch-container">
        <div class="batch-step">
          <div class="step1 step-item">
            <div class="step-item-left">
              <div class="title">第一步：</div>
              <div class="desc">将您的文档按照模板中的格式调整好</div>
              <el-button type="primary" plain size="large" @click="handleDownloadTemp">下载Excel模板</el-button>
            </div>
            <div class="step-item-right">
              <i class="iconfont">&#xe60d;</i>
            </div>
          </div>
          <div class="step2 step-item">
            <div class="step-item-left">
              <div class="title">第二步：</div>
              <div class="desc">调整好格式后，就开始上传文档吧</div>
              <el-upload action="#" accept="xlxs" :show-file-list="false" :http-request="fileUpload">
                <el-button type="primary" size="large">上传Excel模板</el-button>
              </el-upload>
            </div>
            <div class="step-item-right">
              <i class="iconfont">&#xe65c;</i>
            </div>
          </div>
        </div>
        <div class="batch-desc">
          <p>格式说明：</p>
          <p>1、题型名称必须与表单中心提供题型名字一致，否则无法导入。</p>
          <p>2、导入的问题选项中，不要出现|符号。</p>
          <p>3、多选题的正确答案列中，以|作为分隔符。</p>
          <p>4、题型、题目必填，其余项可在批量导入后在编辑器中调整。</p>
        </div>
      </div>
      <template #footer>
        <span>
          <el-button @click="batchAddOpen = false">取消</el-button>
          <el-button type="primary" @click="handleBatchAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref,reactive, computed } from 'vue'
import {
  selectAllQuestion,
  getPublicBank, 
  selectBankQuestionPage,
} from "@/api/formDesign";
import { createTreeData } from '@ruifox-cms/utils'
import { tableList as mixTable } from '@ruifox-cms/utils'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx-js-style'
import { useStore } from 'vuex'
const store = useStore()

const tabArr = ref([
  {id:-1,bankType:2,title:"非考试类",children:[]},
  {id:0,bankType:1,title:"考试类",children:[]}
])
const ptreeData = ref([
  {id:-1,bankType:2,title:"非考试类",children:[]},
  {id:0,bankType:1,title:"考试类",children:[]}
])
const defaultProps = {
  children: 'children',
  label: function (data) {
    return data.title
  }
}
const expandTree = ref(true)
const treeRef = ref(null);
const toggleExpand = () => {
    const nodes = treeRef.value.store.nodesMap
    const newExpandState = !expandTree.value
    Object.keys(nodes).forEach(key => {
        nodes[key].expanded = newExpandState
    })
    expandTree.value = newExpandState
};
const handleGetMybank = () => {
  return new Promise((resolve) => {
    selectAllQuestion().then(res=>{
        tabArr.value.forEach(group => {
            group.children = [];
        });
        const treeData = createTreeData(res.data)
        // 将数据按 bankType 分类到对应组
        treeData.forEach(item => {
            const targetGroup = tabArr.value.find(
              group => group.bankType === item.bankType
            );
            if (targetGroup) {
              targetGroup.children.push(item);
            }

            const _targetGroup = ptreeData.value.find(
              group => group.bankType === item.bankType
            );
            if (_targetGroup) {
              _targetGroup.children.push(item);
            }
        });
        resolve()
    })
  })
}
// 公共题库
const publicBank = ref({})
const handleGetPublicbank = () => {
  return new Promise((resolve) => {
    getPublicBank().then(res=>{
      publicBank.value = res.data
      resolve()
    })
  })
}
const allBankLoading = ref(true)
Promise.all([handleGetMybank(),handleGetPublicbank()]).then(()=>{
  allBankLoading.value = false
  
})

const handleCheckBank = () => {
  dialogVisible.value = true
  //获取题目
  curGroup.value = tabArr.value[0].children[0]
  queryData.id = tabArr.value[0].children[0].id
  // 题库获取成功后，获取题目
  handleResetPagination()
  getTableData();
}

//搜索题目
const searchCmpArray = ref([
  { label: '题目标题', key: 'keyWords' },
//   { label: '题目类型', key: 'itemIdList' },
//   { label: '难度等级', key: 'difficultyLevel' }
])
// 查找第一个children为空的对象
function findFirstEmptyChildren(data) {
    for (const item of data) {
        if (!item.children || item.children.length === 0) {
            return item;
        }
        if (item.children && item.children.length > 0) {
            const result = findFirstEmptyChildren(item.children);
            if (result) return result;
        }
    }
    return null;
}
const handleSearch = async() => {
  const res = await selectAllQuestion({keyWords:queryData.keyWords})
  tabArr.value.forEach(group => {
      group.children = [];
  });
  if(res.data.length > 0) {
      const treeData = createTreeData(res.data)
      // 将数据按 bankType 分类到对应组
      treeData.forEach(item => {
          const targetGroup = tabArr.value.find(
              group => group.bankType === item.bankType
          );
          if (targetGroup) {
              targetGroup.children.push(item);
          }
      });
      //先获取题目分组，再获取题目
      const firstEmptyChildren = findFirstEmptyChildren(treeData)

      curGroup.value = firstEmptyChildren
      queryData.id = firstEmptyChildren.id
      getTableData()

  }else {
      curGroup.value = null
      getTableData()
  }
}

const curGroup = ref()
const dialogVisible = ref(false)
const handleClickOuterNode = (data,node) => {
  if (!node.isLeaf) return
  if (data.id === -1 || data.id === 0) {
        return;
    }
  dialogVisible.value = true
  curGroup.value = data
  queryData.id = data.id
    handleResetPagination()
    getTableData()
}

//点击分组获取题目，只能点叶子节点
const {
  tableLoading,
  checkedList,
  isAllChooseBtn,
  isPageChooseBtn,
  // isAllSearch,
  checkedNum,
  queryData,
  tableData,
  getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectBankQuestionPage
})
const fieldList = ref([
  { title: '题目标题', name: 'label' },
  { title: '类型', name: 'compName' },
  { title: '操作', name: 'options' }
])
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  keyWords:"",
  id:null
})
Object.assign(queryData, defaultQueryData)
const handleClickNode = (data, node) => {
    if (!node.isLeaf) return
    if (data.id === -1 || data.id === 0) {
        return;
    }
    curGroup.value = data
    queryData.id = data.id
    handleResetPagination()
    getTableData()
}
//使用题目
const emit = defineEmits(['formCmpClick','handleBatchInsertQuestions','handleOnePageOneQs']);
const formCmpClick = (cmp) => {
  emit("formCmpClick", cmp);
  dialogVisible.value = false
}
//批量使用题目
const handleBatchUse = () => {
  if(checkedList.value.length > 0) {
    emit("handleBatchInsertQuestions", checkedList.value);
    dialogVisible.value = false
  }else {
    ElMessage({
      message: '请选择题目',
      type: 'warning',
    })
  }
}

  // 获取所有组件列表(去除分页器)
  const componentList = computed(()=>{return store.state.formDesignInfo.componentList.filter(item=>item.type != 'pagenation')})
  const formDesign = computed(()=>{return store.getters.formDesignInfo})
  // 试题模板下载
  const handleDownloadTemp = () => {
  //   let baseApi = process.env.VUE_APP_BASE_API
    const a = document.createElement('a')
  //   a.href = baseApi.replace('/admin_api', '') + '/hcs/doc/questionTemplate.xlsx'
    a.href = '/hcs/doc/questionTemplate.xlsx'
    a.download = '试题导入模板.xlsx'
    document.body.appendChild(a)
    a.click()
    setTimeout(() => {
      document.body.removeChild(a)
    }, 0)
  }
  // 批量添加题目
  const componentListObj = ref()
  const batchAddOpen = ref(false)
  const initComponentListObj = () => {
    // 组件列表对象，以便读取excel后匹配组件
    componentListObj.value = componentList.value.reduce((acc, item) => {
      if (item.compName) {
        acc[item.compName] = item
      }
      return acc
    }, {})
  }
  initComponentListObj()
  const fileUpload = (e) => {
    let formList = []
    const file = e.file
    if (!file) return
    const reader = new FileReader()
    reader.onload = (e) => {
      const data = e.target.result
      const workbook = XLSX.read(data, { type: 'binary' })
      const sheetName = workbook.SheetNames[0]
      const sheet = workbook.Sheets[sheetName]
      const qsData = XLSX.utils.sheet_to_json(sheet, { raw: false })
      // 处理json数据
      qsData.forEach(item => {
        const {
          题型: compName,
          题目: label,
          题目描述: description,
          正确答案: referAnswer,
          答案解析: referAnalysis,
          分值: referScore
        } = item
        let tempComp = componentListObj.value[compName]
        if (tempComp) {
          let newCmp = JSON.parse(JSON.stringify(tempComp))
          newCmp.formItemId = newCmp.type + "_" + Date.now() + "_" + Math.ceil(Math.random() * 99999)
          label === undefined ? '' : newCmp.label = label
          referAnalysis === undefined ? '' : newCmp.referAnalysis = referAnalysis
          referScore === undefined ? '' : newCmp.referScore = Number(referScore)
          description === undefined ? '' : newCmp.description = description
          // 多选类型答案处理
          if(referAnswer !== undefined){
            if('checkbox|selectMultiple'.includes(newCmp.type)){
              newCmp.referAnswer = referAnswer.split('|')
            }else{
              newCmp.referAnswer = referAnswer
            }
          }
          // 选项处理(提取出属性名包含选项二字的属性值)
          const optionValues = Object.keys(item).filter(key => key.includes('选项'))
          if (optionValues.length) {
            newCmp.default = optionValues.map(key => {
              return {
                connect: [],
                label: item[key],
                optionFile: "",
                placeholder: key,
              }
            })
          }
          formList.push(newCmp)
        }
      })
      formDesign.value.formItemList.push(...formList)
      if(formDesign.value.onePageOneQs) {
        emit("handleOnePageOneQs");
      }
      batchAddOpen.value = false
    }
    reader.readAsBinaryString(file);
  }
  const handleBatchAddConfirm = () => {
    batchAddOpen.value = false
  }
</script>
<style lang="scss" scoped>
.bank-container {
  padding: 0px 20px;
  .qs-bank{
    margin-top: 20px;
    .bank-title{
      margin-bottom: 20px;
      color: #000;
      font-weight: 600;
      font-style: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .questions-bank {
      border: 1px $borderColor solid;
      .tree-header {
        height: 53px;
        background-color: $backBase;
        border-bottom: 1px solid $borderColor;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .tree-content {
        ::v-deep .el-tree-node .el-tree-node__content {
          border-bottom: 1px solid $borderColor;
          height: 48px;
        }
        ::v-deep .el-tree-node__label {
          width: 100%;
          .custom-tree-node {
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;
              .tree-node-label {
              width: calc(100% - 16px - 26px);
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              }
              .tree-options {
              display: flex;
              padding-right: 10px;
              flex-shrink: 0;
              }
              .tree-num {
                  padding-right: 10px;
              }
          }
        }
      }
    }
  }
  .myQsBank-dialog {
    .content-box {
      margin-top: 10px;
        /* min-height: 70vh; */
        border: 1px $borderColor solid;
        ::v-deep(.el-scrollbar__view) {
        height: 100%;
        }
        .menu-tree-box {
        overflow: hidden;
        border-right: 1px solid $borderColor;
        .custom-tree-node {
            display: flex;
        }
        .tree-header {
            height: 53px;
            background-color: $backBase;
            border-bottom: 1px solid $borderColor;
            padding: 0 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .tree-content {
            ::v-deep .el-tree-node .el-tree-node__content {
            border-bottom: 1px solid $borderColor;
            height: 48px;
            }
            ::v-deep .el-tree-node__label {
            width: 100%;
            .custom-tree-node {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                .tree-node-label {
                width: calc(100% - 16px - 26px);
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                }
                .tree-options {
                display: flex;
                padding-right: 10px;
                flex-shrink: 0;
                }
                .tree-num {
                    padding-right: 10px;
                }
            }
            }
        }
        }
        .qs-table {
        .user-table-top {
            padding: 15px;
            background: #dfe9f5;
            display: flex;
            justify-content: space-between;
            .top-left {
            .curOStructure {
                color: #666;
            }
            .user-default-show {
                color: #666;
            }
            .user-total {
                color: $mainColor;
            }
            }
        }
        }
    }
  }
  .el-dialog.batch-dialog{
        .batch-container{
        padding: 0 20px;
        .batch-step{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            .step-item{
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: calc((100% - 10px) / 2);
            box-sizing: border-box;
            padding: 20px;
            border: 1px solid #E8E8E8 ;
            .step-item-left{
                display: flex;
                flex-direction: column;
                margin-right: 20px;
                .title{
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 10px;
                }
                .desc{
                font-size: 14px;
                color: #9C9C9C;
                margin-bottom: 10px;
                }
            }
            .step-item-right i{
                font-size: 100px;
                color: #cccccc;
            }
            }
            .step2{
            background: #f7f7f7;
            }
        }
        .batch-desc{
            font-size: 14px;
            color: #9C9C9C;
            p{
            margin-bottom: 4px;
            }
        }
        }
    }
}
</style>